package com.zhoumy.juc.tl;


import java.util.Random;
import java.util.concurrent.TimeUnit;

class House2 { //资源类
    int saleCount = 0;

    //需求1 写法
    public synchronized void saleHouse() {
        saleCount++;
    }

    /**
     * java8之前的写法，此功能用withInitial(java8之后的写法)
     */
    /*ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };*/

    //需求2 写法
    ThreadLocal<Integer> saleVolume = ThreadLocal.withInitial(() -> {
        return 0;
    });

    public void saleVolumeByThreadLocal() {
        saleVolume.set(saleVolume.get() + 1);
    }


}

/**
 * @author zhoumy
 * @create 2024年6月19日09:22:11
 * 需求2： 需求：需求变更：希望各自分灶吃饭，各凭销售本事提成，按照出单数各自统计-------比如房产中介销售都有自己的销售额指标，自己专属自己的，不和别人参和。
 */
public class ThreadLocalDemo2 {
    public static void main(String[] args) {
        House2 house2 = new House2();
        for (int i = 1; i <= 5; i++) {
            new Thread(() -> {
                int size = new Random().nextInt(5) + 1;
                //System.out.println(size);
                try {
                    for (int j = 1; j <= size; j++) {
                        house2.saleHouse();
                        house2.saleVolumeByThreadLocal();
                    }
                    System.out.println(Thread.currentThread().getName() + "\t" + "号销售卖出：" + house2.saleVolume.get());
                } finally {
                    house2.saleVolume.remove();
                }
            }, String.valueOf(i)).start();
        }
        try {
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "\t" + "共计卖出多少套： " + house2.saleCount);
    }
}